package com.sunspring.jbug.aop;

import com.sunspring.jbug.bean.UserInfo;
import com.sunspring.jbug.common.constant.HttpConstant;
import com.sunspring.jbug.common.exception.JbugException;
import com.sunspring.jbug.support.ContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: wulei
 * @Date: 2019/3/8
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfo currentUser = (UserInfo) request.getSession().getAttribute(HttpConstant.SessionKey);
        if (currentUser == null) {
            throw new JbugException("会话过期");
        }
        ContextHolder.add(currentUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ContextHolder.remove();
    }
}
